/*
 * Copyright (c) 2011-2021, baomidou (jobob@qq.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.baomidou.mybatisplus.extension.plugins.inner;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ParameterUtils;
import com.baomidou.mybatisplus.core.toolkit.mapping.ParameterValueMapping;
import com.baomidou.mybatisplus.extension.plugins.handler.ClearCacheHandler;
import com.baomidou.mybatisplus.extension.plugins.handler.DataPermissionHandler;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;

import java.sql.SQLException;
import java.util.List;

/**
 * 缓存清理拦截处理器
 *
 * @author hejianxiong
 * @since 3.5.7 +
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString(callSuper = true)
public class ClearCacheInterceptor implements InnerInterceptor {

    /**
     * 清理缓存处理函数
     */
    private ClearCacheHandler clearCacheHandler;

    @Override
    public void beforeUpdate(Executor executor, MappedStatement ms, Object parameter) throws SQLException {
        if (SqlCommandType.UPDATE != ms.getSqlCommandType()) {
            return;
        }
        // 清理缓存
        List<ParameterValueMapping> parameterValueMappingList = ParameterUtils.getParameterMapping(ms.getConfiguration(), ms.getBoundSql(parameter));
        if (CollectionUtils.isEmpty(parameterValueMappingList)){
            return;
        }
        clearCacheHandler.clearCache(ms.getId(), parameterValueMappingList);
    }
}
